package com.steven;

import javax.swing.*;
import javax.swing.border.BevelBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Objects;
import java.util.Properties;

public class MainViewer extends JFrame {
    String weChatLoc = "---";
    int wechat_count = 0;
    int wechat = 1;
    Runtime runtime = Runtime.getRuntime();
    String sys_encode = "GBK";

    static {
        // 加载UI
        try {
//            去除顶部设置按钮
            UIManager.put("RootPane.setupButtonVisible", false);
            org.jb2011.lnf.beautyeye.BeautyEyeLNFHelper.launchBeautyEyeLNF();
            // jframe对象需要放在加载UI主题包之后,初始化,否则可能会造成部分效果设置不生效的问题
        } catch (Exception e) {
            JOptionPane.showMessageDialog(new MainViewer(), "UI主题包设置异常!!!");
        }
    }

    public MainViewer() {
        this.setTitle("微信多开器");
        this.setSize(600, 400);
        this.setResizable(false);
        this.setLocationRelativeTo(null);


        // 加载背景图片
        ImageIcon bg_icon = new ImageIcon(Objects.requireNonNull(getClass().getResource("/appImage/bg.jpg")));
        JLabel bg_label = new JLabel(bg_icon);
        bg_label.setBounds(0, 0, bg_icon.getIconWidth(), bg_icon.getIconHeight());
        // 图片大小约束 必须使用new Integer() 构造方法的姓氏 , 否则会出现上方的导航条遮挡消失
        this.getLayeredPane().add(bg_label, new Integer(Integer.MIN_VALUE));

        final ImageIcon icon = new ImageIcon(Objects.requireNonNull(getClass().getResource("/appImage/WeChat.jpg")));
        this.setIconImage(icon.getImage());

        final JPanel left = new JPanel(new GridLayout(5, 5, 5, 5));
        left.setPreferredSize(new Dimension(toInt(this.getWidth() * 0.5), this.getHeight()));
        left.setBorder(new BevelBorder(2, new Color(243, 221, 15), new Color(243, 221, 15)));

        JPanel right = new JPanel(new GridLayout(2, 1));
        right.setPreferredSize(new Dimension(toInt(this.getWidth() * 0.3), this.getHeight()));
        right.setBorder(new BevelBorder(2, new Color(243, 221, 15), new Color(243, 221, 15)));
        final JButton hasLogged = new JButton("已开启 : " + wechat_count + "");
        setMyCSS(hasLogged, 25, Color.RED);

        JButton newInstance = new JButton("+ 多开 +");
        setMyCSS(newInstance, 30, Color.GREEN);
        newInstance.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int shutdownConfirmDialog = JOptionPane.showConfirmDialog(MainViewer.this, "多开前要关闭已登陆的微信 , 是否确认?");
                if (shutdownConfirmDialog == 0) {
                    final JDialog dialog = new JDialog(MainViewer.this, "设置多开个数");
                    dialog.setIconImage(icon.getImage());
                    dialog.setSize(getWidth() / 4 * 3, getHeight() / 4 * 3);
                    dialog.setLocationRelativeTo(MainViewer.this);
                    dialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
                    JPanel panel = new JPanel(new BorderLayout());
                    dialog.add(panel);


                    final JTextField field = new JTextField(10);
                    field.setPreferredSize(new Dimension(dialog.getWidth(), dialog.getHeight() / 3));
                    field.setText("" + wechat);
                    field.setFont(new Font("楷体", Font.BOLD, 30));
                    JButton sure = new JButton("确定");
                    sure.setFont(new Font("楷体", Font.BOLD, 30));
                    panel.add(field, BorderLayout.NORTH);
                    panel.add(sure, BorderLayout.CENTER);

                    sure.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            String count = field.getText();
                            try {
                                wechat = Integer.parseInt(count);
                                dialog.setVisible(false);
                            } catch (Exception pe) {
                                JOptionPane.showMessageDialog(dialog, "输入错误, 只能输入数字!");
                            }
                        }
                    });
                    dialog.setVisible(true);

                    int startConfirmDialog = JOptionPane.showConfirmDialog(MainViewer.this, "即将关闭已开启的微信 , 再次确认是否同意?");
                    if (startConfirmDialog == 0) {
                        // 关闭已开启的微信 ,
                        closeWechat();
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException ex) {
                            ex.printStackTrace();
                        }
                        // 开启新微信
                        startWechat();
                    }
                }
            }

        });

        right.add(hasLogged);
        right.add(newInstance);

        this.getLayeredPane().setOpaque(false);
        left.setOpaque(false);
        right.setOpaque(false);
        this.add(left, BorderLayout.WEST);
        this.add(right, BorderLayout.CENTER);


        new Thread() {
            @Override
            public void run() {
                try {
                    int last = 0;
                    while (true) {
                        check();
                        hasLogged.setText("已开启 : " + wechat_count + "");
                        if (last != wechat_count) {
                            left.removeAll();
                            for (int i = 0; i < wechat_count; i++) {
                                final ImageIcon icon = new ImageIcon(Objects.requireNonNull(getClass().getResource("/appImage/already.jpg")));
                                left.add(new JLabel(icon, JLabel.CENTER));

                                left.repaint();
                                MainViewer.this.repaint();
                            }
                            for (int i = 0; i < 25 - wechat_count; i++) {
                                left.add(new JLabel(""));
                            }
                            MainViewer.this.setVisible(true);
                        }
//                        System.out.println(last+"-----------");
                        last = wechat_count;
//                        MainViewer.this.setVisible(true);
                        Thread.sleep(1000);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }.start();
        this.setVisible(true);
        loadTrayIcon(icon);
//        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    private void check() throws IOException {

        ArrayList<String> tasklist = new ArrayList<>();

        String chcp = "cmd /c chcp";
        Process process_chcp = runtime.exec(chcp);
        InputStream chcp_in = process_chcp.getInputStream();
        BufferedReader chcp_reader = new BufferedReader(new InputStreamReader(chcp_in));
        String chcp_res = chcp_reader.readLine().split(":")[1].trim();
        switch (chcp_res) {
            case "936":
                sys_encode = "GBK";
                break;
            case "65001":
                sys_encode = "UTF-8";
                break;
        }

        //----------------------------------------------------------------------------------------//
        String cmd = "cmd /c tasklist";
        Process process_cmd = runtime.exec(cmd);
        InputStream inputStream = process_cmd.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, sys_encode));
        String line;
        while ((line = reader.readLine()) != null) {
            tasklist.add(line);
//            System.out.println(line);
        }
        wechat_count = 0;
        for (String task : tasklist) {
            if (task.contains("WeChat.exe")) {
                wechat_count++;
            }
        }
//        System.out.println(wechat_count);
        File loc = new File("WeChatLocation.properties");
        if (!loc.exists()) {
            if (wechat_count == 0) {
                // 没有记录文件, 不知道微信的安装位置, 则提醒用户打开微信, 找到微信的安装位置, 并记录到文件中
                JOptionPane.showMessageDialog(MainViewer.this, "未找到微信, 如果是第一次使用, 请打开微信软件, 无需登录, 仅微信的安装位置!");
            } else {
                searchWeChatLocation(); // 找到了以后记录微信的安装位置
                if (!"---".equals(weChatLoc)) {
                    loc.createNewFile();
                    BufferedWriter writer = new BufferedWriter(new FileWriter(loc));
                    Properties prop_loc = new Properties();
                    prop_loc.setProperty("wcLOC", weChatLoc);
                    prop_loc.store(writer, "update WeChat location");
                    JOptionPane.showMessageDialog(MainViewer.this, "已记录微信的安装位置, 点击确定继续操作!");
                    // 关闭微信
                    closeWechat();
                    // runtime.exec("cmd /c taskkill /f /t /im wechat.exe");
                }
            }
        } else {
            // 已经知道了微信的安装位置, 直接从文件中读取位置
            Properties prop_loc = new Properties();
            BufferedReader br = new BufferedReader(new FileReader(loc));
            prop_loc.load(br);
            String wcLOC = prop_loc.getProperty("wcLOC");
            weChatLoc = wcLOC;
        }
        reader.close();
    }

    public int toInt(Double d) {
        return (int) d.doubleValue();
    }

    public void setMyCSS(Component component, int fontSize, Color color) {
        component.setFont(new Font("楷体", Font.BOLD, fontSize));
        component.setForeground(color);
    }

    // 加载 托盘程序
    public void loadTrayIcon(ImageIcon icon) {

        TrayIcon trayIcon = null;
        if (SystemTray.isSupported()) // 判断系统是否支持系统托盘
        {
            SystemTray tray = SystemTray.getSystemTray(); // 创建系统托盘
            // 载入图片,这里要写你的图标路径哦
            icon.setImage(icon.getImage().getScaledInstance(15, 15, Image.SCALE_DEFAULT));
            ActionListener listener = new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    MainViewer.this.setVisible(true);
                }
            };
            // 创建弹出菜单
            PopupMenu popup = new PopupMenu();
            //主界面选项
            MenuItem mainFrameItem = new MenuItem("OPEN");
            mainFrameItem.addActionListener(listener);

            //退出程序选项
            MenuItem exitItem = new MenuItem("EXIT");
            exitItem.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    if (JOptionPane.showConfirmDialog(null, "确定退出系统") == 0) {
                        System.exit(0);
                    }
                }
            });

            popup.add(mainFrameItem);
            popup.add(exitItem);

            trayIcon = new TrayIcon(icon.getImage(), "微信多开", popup);// 创建trayIcon
            trayIcon.addActionListener(listener);
            try {
                tray.add(trayIcon);
            } catch (AWTException e1) {
                e1.printStackTrace();
            }
        } else {
            System.out.println("----------------------------");
        }
    }

    // 搜索微信的安装位置
    private void searchWeChatLocation() throws IOException {
        ArrayList<String> loclist = new ArrayList<>();
        String cmd = "cmd /c wmic process get Caption^,ExecutablePath";
        Process process_cmd = runtime.exec(cmd);
        InputStream inputStream = process_cmd.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, sys_encode));
        String line;
        while ((line = reader.readLine()) != null) {
            loclist.add(line);
//            System.out.println(line);
        }
        wechat_count = 0;
        for (String loc : loclist) {
            if (loc.contains("WeChat.exe")) {
                weChatLoc = loc.split("\\s{2,}")[1];
                weChatLoc = weChatLoc.substring(0, weChatLoc.length() - 10);
                break;
            }
        }
//        System.out.println(wechat_count);
        reader.close();
    }

    private void closeWechat(){
        // taskkill /f /t /im
        try {
            StringBuffer shutdown = new StringBuffer();
//                sb.append("%1 mshta vbscript:CreateObject(\"Shell.Application\").ShellExecute(\"cmd.exe\",\"/c %~s0 ::\",\"\",\"runas\",1)(window.close)&&exit\n");
            //
            shutdown.append("%1 mshta vbscript:CreateObject(\"Shell.Application\").ShellExecute(\"cmd.exe\",\"/c \"^&chr(34)^&\"%~0\"^&chr(34)^&\" ::\",\"%cd%\",\"runas\",1)(window.close)&&exit\n");
            shutdown.append("@echo off\n");
            shutdown.append("cmd /c taskkill /f /t /im wechat.exe\n");
            shutdown.append("exit\n");

            File shutdownbatfile = new File("shutdownWeChat.bat");
            BufferedWriter shutdownwriter = new BufferedWriter(new FileWriter(shutdownbatfile));
            shutdownwriter.write(shutdown.toString());
            shutdownwriter.flush();
            shutdownwriter.close();

            runtime.exec(shutdownbatfile.getAbsolutePath());
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    private void startWechat(){
        StringBuffer sb = new StringBuffer();
        sb.append("%1 mshta vbscript:CreateObject(\"Shell.Application\").ShellExecute(\"cmd.exe\",\"/c \"^&chr(34)^&\"%~0\"^&chr(34)^&\" ::\",\"%cd%\",\"runas\",1)(window.close)&&exit\n");
        sb.append("@echo off\n");

        for (int i = 0; i < wechat; i++) {
            sb.append("start /d \"" + weChatLoc + "\" WeChat.exe\n");
        }
        // sb.insert(sb.length()-4,"start /d \"C:\\Program Files (x86)\\Tencent\\WeChat\\\" WeChat.exe\n");
        sb.append("exit");
        System.out.println(sb.toString());

        try {
            File batfile = new File("openWeChat.bat");
            BufferedWriter writer = new BufferedWriter(new FileWriter(batfile));
            writer.write(sb.toString());
            writer.flush();
            writer.close();

            runtime.exec("cmd /c " + batfile.getAbsolutePath());
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }
}
